<?php
namespace tlan_turing\migration\command\seed;
use Phinx\Util\Util;
use think\console\Input;
use think\console\input\Argument as InputArgument;
use think\console\Output;
use tlan_turing\migration\command\Seed;

class Create extends Seed
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this->setName('seed:create')
            ->setDescription('Create a new database seeder')
            ->addArgument('name', InputArgument::REQUIRED, 'What is the name of the seeder?')
            ->setHelp(sprintf('%sCreates a new database seeder%s', PHP_EOL, PHP_EOL));
    }

    /**
     * Create the new seeder.
     *
     * @param Input  $input
     * @param Output $output
     * @return void
     * @throws \InvalidArgumentException
     * @throws \RuntimeException
     */
    protected function execute(Input $input, Output $output)
    {
        $className  = trim($input->getArgument('name'));
        if (str_contains($className, '@')) {
            [$app, $name] = explode('@', $className);
        } else {
            $app = '';
            $name = $className;
        }
        $path = $this->getPath($app);



        if (!file_exists($path)) {
            mkdir($path, 0755, true);
        }

        $this->verifyMigrationDirectory($path);

        $path = realpath($path);



        if (!Util::isValidPhinxClassName($name)) {
            throw new \InvalidArgumentException(sprintf('The seed class name "%s" is invalid. Please use CamelCase format', $name));
        }

        // Compute the file path
        $filePath = $path . DIRECTORY_SEPARATOR . $name . '.php';

        if (is_file($filePath)) {
            throw new \InvalidArgumentException(sprintf('The file "%s" already exists', basename($filePath)));
        }

        // inject the class names appropriate to this seeder
        $contents = file_get_contents($this->getTemplate());
        $classes  = [
            'SeederClass' => $name,
        ];
        $contents = strtr($contents, $classes);

        if (false === file_put_contents($filePath, $contents)) {
            throw new \RuntimeException(sprintf('The file "%s" could not be written to', $path));
        }

        $output->writeln('<info>created</info> .' . str_replace(getcwd(), '', $filePath));
    }

    protected function getTemplate()
    {
        return __DIR__ . '/../stubs/seed.stub';
    }

    protected function getClassName(string $name): string
    {
        if (str_contains($name, '\\')) {
            return $name;
        }



        if (str_contains($name, '@')) {
            [$app, $name] = explode('@', $name);
        } else {
            $app = '';
        }

        if (str_contains($name, '/')) {
            $name = str_replace('/', '\\', $name);
        }

        return  $name;
    }
}